package com.sec.android.app.myfiles.util;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Toast;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.navigation.NavigationInfo;

/**
 * Task that creates a new document in the background.
 */
public class CreateDocumentTask extends AsyncTask<Void, Void, Bundle> {
    private static final String EXTRA_CONTENT_URI = "CONTENT_URI";
    private static final String EXTRA_FILE_URI = "FILE_URI";

    private Activity mActivity;
    private Context mContext;
    private NavigationInfo mNavigationInfo;
    private final String mMimeType;
    private final String mDisplayName;
    private final String mExtension;

    public CreateDocumentTask(Activity activity, NavigationInfo navigationInfo, String mimeType, String displayName, String extension) {
        mActivity = activity;
        mContext = activity.getApplicationContext();

        mNavigationInfo = navigationInfo;

        mMimeType = mimeType;
        mDisplayName = displayName;
        mExtension = extension;
    }

    @Override
    protected Bundle doInBackground(Void... params) {
        final ContentResolver resolver = mContext.getContentResolver();

        Uri contentUri = null;
        Uri fileUri = null;
        Log.d(this, "doInBackground() -" + mDisplayName + ":" + mMimeType);
        try {
            String path = mNavigationInfo.getCurRecord().getFullPath();

            File file = SemFwWrapper.file(path, mDisplayName + "." + mExtension);
            int n = 1;
            while (file.exists()) {
                file = SemFwWrapper.file(path, mDisplayName + "(" + n + ")." + mExtension);
                n++;
            }

            if (!file.createNewFile()) {
                Log.e(this, "create failed.");
                return null;
            }

            ContentValues values = new ContentValues();
            values.put(MediaStore.Files.FileColumns.DATA, file.getAbsolutePath());
            values.put(MediaStore.Files.FileColumns.SIZE, file.length());
            values.put(MediaStore.Files.FileColumns.MIME_TYPE, mMimeType);
            values.put(MediaStore.Files.FileColumns.TITLE, mDisplayName);
            values.put(MediaStore.Files.FileColumns.DISPLAY_NAME, file.getName());

            contentUri = resolver.insert(FileUtils.MEDIA_PROVIDER_URI, values);
            fileUri = Uri.fromFile(file);

        } catch (IOException e) {
            Log.e(this, "IOException:" + e.toString());
        } catch (Exception e) {
            Log.e(this, "Failed to create document:" + e.toString());
        }

        Bundle bundle = new Bundle();
        bundle.putParcelable(EXTRA_CONTENT_URI, contentUri);
        bundle.putParcelable(EXTRA_FILE_URI, fileUri);
        return bundle;
    }

    @Override
    protected void onPostExecute(Bundle bundle) {
        Uri result = bundle.getParcelable(EXTRA_CONTENT_URI);
        Uri fileUri = bundle.getParcelable(EXTRA_FILE_URI);

        Log.d(this, "onPostExecute() " + result);

        if (result != null) {
            final Intent intent = new Intent();

            intent.setData(result);
            intent.putExtra(EXTRA_FILE_URI, fileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

            mActivity.setResult(Activity.RESULT_OK, intent);

            mActivity.finish();
        } else {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.error), Toast.LENGTH_SHORT).show();
        }
    }
}
